import React, { Component } from "react"
import ReactDOM from "react-dom"
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { Page } from '../components/page'
import Actions from '../Actions'

var modules = {
    toolbar: [
        ['bold', 'italic', 'underline', 'strike', 'blockquote'],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
        ['link'],
        ['clean']
    ],
}
var formats = [
    'bold', 'italic', 'underline', 'strike', 'blockquote',
    "align",
    'list', 'bullet', 'indent',
    'link'
]
require("./video.css")
export default class Video extends Component {

    constructor(prop) {
        super(prop)
        this.state = { videoInfo: {}, videosProgress: null }
    }

    componentDidMount() {
        console.log("id", this.props.params.id)
        if (this.props.params.id) {
            Actions.VideoActions.getVideoInfo({ id: this.props.params.id }).then(res => {
                let videoInfo = JSON.parse(res);
                this.setState({ videoInfo })
            });
        }
    }

    _createPlay() {
        Actions.VideoActions.createVideo({ ...this.state.videoInfo }).then(res => {
            let videoInfo = res ? JSON.parse(res) : {};
            if (videoInfo.id) {
                this.setState({ videoInfo: videoInfo })
                toastr.success("操作成功")
            }

        })
    }
    _editPlayInfo() {
        let videoInfo = { ...this.state.videoInfo }
        Actions.VideoActions.updateVideo(videoInfo).then(res => {
            if (res) {
                toastr.success("操作成功")
            }
        })
    }
    _update(update) {
        this.setState({ videoInfo: { ...this.state.videoInfo, ...update } })
    }

    submit() {
        if (this.state.videoInfo.id) {
            this._editPlayInfo()
        } else {
            this._createPlay()
        }

    }

    render() {
        let state = { ...this.state }
        return <div className="content-wrapper">
            <div className="panel panel-default">

                <div className="panel-heading">
                    <span className="glyphicon glyphicon-arrow-left" ><a href={`${location.pathname}#/historyVideo`}>返回列表</a></span>

                    <span className="pull-right">
                        <a onClick={this.submit.bind(this)} ><span className="glyphicon glyphicon-plus" aria-hidden="true">提交</span></a>
                    </span>

                </div>
                <div className="panel-body">
                    <div className="table-responsive">
                        <div>
                            <div className="form-group">
                                <label>视频名称</label>
                                <input className="form-control" value={state.videoInfo.name}
                                    onChange={(event) => this._update({ name: event.target.value })}
                                />
                            </div>
                            <div className="form-group">
                                <label>视频</label>
                                <input ref="file" style={{ display: this.state.videoInfo.videoUrl ? "none" : "block" }} accept=".mp4" onChange={(e) => {
                                    e.preventDefault();
                                    if (this.refs.file.files.length > 0) {
                                        var formData = new FormData();
                                        formData.append("file", this.refs.file.files[0]);
                                        $.ajax({
                                            type: 'POST',
                                            url: '/upload',
                                            cache: false,
                                            contentType: false,
                                            processData: false,
                                            data: formData,
                                            success: (response, textStatus, jqXHR) => {

                                                this._update({ videoUrl: "/upload/" + response.filename })
                                            },
                                            error: function (jqXHR, textStatus, errorThrown) {
                                                toastr.error("上传视频失败", textStatus)
                                            },
                                            xhr: () => {
                                                var myXhr = $.ajaxSettings.xhr();
                                                if (myXhr.upload) {
                                                    myXhr.upload.addEventListener(
                                                        'progress', (event) => {
                                                            let videosProgress = this.state.videosProgress;
                                                            videosProgress = event.loaded / event.total
                                                            console.log(videosProgress)
                                                            if (event.loaded >= event.total) {
                                                                this.setState({ videosProgress: null })
                                                            } else {
                                                                this.setState({ videosProgress })
                                                            }
                                                        }, false);
                                                }
                                                return myXhr;
                                            }
                                        });
                                    }
                                }} type="file" />

                                {
                                    this.state.videosProgress && <label>已完成{this.state.videosProgress}</label>
                                }
                                {
                                    state.videoInfo.videoUrl && <video onClick={() => { this.refs.file.click() }} src={{ ...state.videoInfo }.videoUrl} style={{ width: "200px", height: "200px" }} controls="controls">您的浏览器不支持 video 标签。</video>
                                }

                            </div>
                            <div className="form-group">
                                <label>备注</label>
                                <input className="form-control" value={state.videoInfo.customize}
                                    onChange={(event) => this._update({ customize: event.target.value })}
                                />
                            </div>
                            <div className="form-group video">
                                <label>视频简介</label>
                                <ReactQuill
                                    value={{ ...state.videoInfo }.info || ''}
                                    modules={modules}
                                    formats={formats}
                                    onChange={(value, delta, source, editor) => {
                                        this._update({ info: value })
                                    }}
                                />
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    }

}

export class HistoryVideo extends Component {

    constructor(prop) {
        super(prop)
        this.state = { historyVideos: {}, playVideo: {} }
    }


    componentDidMount() {
        Actions.VideoActions.getPlayVideo().then(res => {
            try {

                let playVideo = JSON.parse(res);
                this.setState({ playVideo })
            } catch (error) {

            }
            this._getHistoryVideos()
        })
    }


    // componentWillReceiveProps(nextProps) {
    //     // console.log(this.props.params.page)
    //     if (this.props.params != nextProps.params) {
    //         this._getHistoryVideos(nextProps.params.page);
    //     }
    // }

    _getHistoryVideos(page) {
        Actions.VideoActions.getAllVideo({ page: page || 0, size: 30 }).then(res => {
            let historyVideos = res ? JSON.parse(res) : {}
            this.setState({ historyVideos: historyVideos })
        })
    }
    _setPlayInfo(videoId) {
        Actions.PlayInfoActions.setPlayInfo({ id: videoId }).then(res => {
            Actions.VideoActions.getAllVideo({ page: 0, size: 30 }).then(res => {
                let historyVideos = res ? JSON.parse(res) : {}
                this.setState({ historyVideos: historyVideos, playVideo: { id: videoId } })
            })
        });
    }
    _delete(id) {
        let message = prompt("请输入\“确认删除\”")
        if (message === "确认删除") {
            Actions.VideoActions.deleteVideo(id).then(res => {
                Actions.VideoActions.getPlayVideo().then(res => {
                    try {
                        let playVideo = JSON.parse(res);
                        this.setState({ playVideo })
                    } catch (error) {

                    }
                    this._getHistoryVideos()
                })
            })
        }
    }
    render() {
        let state = { ...this.state }
        return <div className="content-wrapper">
            <div className="panel panel-default">
                <div className="panel-heading">
                    视频管理
                    <span className="pull-right"><a href={`${location.pathname}#/playVideo`}>添加视频</a></span>
                </div>
                <div className="panel-body">
                    <div className="table-responsive">
                        <table className="table table-striped table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>视频名称</th>
                                    <th>创建时间</th>
                                    <th>最后修改时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {state.historyVideos.content && state.historyVideos.content.map((item, key) => {
                                    return <tr style={this.state.playVideo.id === item.id ? { backgroundColor: "#cccccc" } : {}} key={key}>
                                        <td>{this.state.playVideo.id !== item.id ? key + 1 : <i className="glyphicon glyphicon-play-circle"></i>}</td>
                                        <td>{item.name}</td>
                                        <td>{moment(item.createTime).format('YYYY.MM.DD')}</td>
                                        <td>{moment(item.lastModifiedTime).format('YYYY.MM.DD')}</td>
                                        <td>
                                            <a className="btn btn-info" href={`${location.pathname}#/playVideo/${item.id}`} >修改</a>
                                            <a className="btn btn-danger" onClick={this._delete.bind(this, item.id)}>删除</a>
                                            {this.state.playVideo.id !== item.id ? <a onClick={this._setPlayInfo.bind(this, item.id)}>设置为在播视频</a> : null}
                                        </td>
                                    </tr>
                                })}
                            </tbody>
                        </table>

                        {(state.historyVideos.totalPages && state.historyVideos.totalPages > 1) ?
                            <Page data={{ ...state.historyVideos }} number={{ ...this.state.historyVideos }.number} handle={(page) => {
                                location.hash = `#/historyVideo/${page}`
                            }} />
                            : null
                        }
                    </div>
                </div>
            </div>
        </div>
    }
}